package com.axinfu.util.validjsonq.loader;

import com.alibaba.fastjson.JSONObject;
import com.axinfu.util.EmptyUtil;
import com.axinfu.util.validjsonq.ValidQLoader;
import com.axinfu.util.validq.BaseValidator;
import com.axinfu.util.validq.ValidQ;

import java.util.HashMap;
import java.util.Map;

/**
 * BaseLoader
 *
 * @author zjn
 * @since 2022/3/23
 */
@SuppressWarnings(value = "unused")
public abstract class BaseLoader implements ValidQLoader {

    /**
     * loadValidQ
     *
     * @param validQ             validQ
     * @param validationConfig   validationConfig
     * @param target             target
     * @param attrField          attrField
     * @param attrShortField     attrShortField
     * @param attrFieldName      attrFieldName
     * @param attrShortFieldName attrShortFieldName
     * @param level              level
     * @param index              index
     * @param validator          validator
     * @param msg                msg
     */
    protected void loadValidQ(ValidQ validQ, JSONObject validationConfig, Object target, String attrField,
                              String attrShortField, String attrFieldName, String attrShortFieldName,
                              Integer level, Integer index,
                              BaseValidator validator, String msg) {

        validator.setField(attrField);
        validator.setShortField(attrShortField);
        validator.setFieldName(attrFieldName);
        validator.setShortFieldName(attrShortFieldName);

        if (EmptyUtil.isNotEmpty(msg)) {
            Map<String, String> defaultParams = new HashMap<>(5);
            defaultParams.put("ctx.field", attrField);
            defaultParams.put("ctx.shortField", attrShortField);
            defaultParams.put("ctx.fieldName", attrFieldName);
            defaultParams.put("ctx.shortFieldName", attrShortFieldName);
            defaultParams.put("ctx.target", String.valueOf(target));
            validator.setErrorMsg(validQ.getContext().replaceParams(msg, defaultParams));
        }

        index = null == index ? validator.index() : index;
        ValidQ on = validQ.on(target, validator, level, index);
    }
}
